<template>
	<view style="height: 100%">
		<view class="cardContainer" :style="{marginLeft: cardMargin}">
			<view v-for="item in 2" :key="item" class="card" @touchstart="moveStart" @touchend="moveEnd">
				<view class="maskSqu"></view>
				<view class="maskRou"></view>
				<view class="cardTitle line">
					<view>
						{{item==1?'基金':'股票'}}收益
					</view>
					<view class="eye">
						<image @click="openEye = !openEye" src="../../static/image/smile.png" v-if="openEye"></image>
						<image @click="openEye = !openEye" src="../../static/image/dizzy.png" v-else></image>
					</view>
				</view>
				<view class="proceed line" :class="proceed >= 0 ? 'text-red' : 'text-green'">
					<view>
						￥ {{openEye ? proceed : '****'}}
					</view>
				</view>
				<view class="cardNumber line">
					<view>
						CARD NUMBER
						<br>
						8888 8888 8888 666
					</view>
					<view class="cardDate">
						DATE
						<br>
						{{date}}
					</view>
				</view>
			</view>
		</view>
		<view class="header-box">
			<view v-if="!setting" class="list-header padding cu-bar bg-white solid-bottom flex">
				<view class="flex-sub text-center text-bold">名称/代码</view>
				<view class="flex-sub text-center text-bold">{{
          showFund? "昨日净值" : "最新价"
        }}</view>
				<view class="flex-sub text-center text-bold">{{
          showFund ? "今日估值" : "涨跌幅"
        }}</view>
				<view class="flex-sub text-center text-bold">{{
          showFund ? "预估收益" : "实时收益"
        }}</view>
			</view>
			<view v-else class="list-header padding cu-bar bg-white solid-bottom flex">
				<view class="flex-sub text-center text-bold">名称/代码</view>
				<view class="flex-sub text-center text-bold">持有金额</view>
				<view class="flex-sub text-center text-bold">操作</view>
			</view>
		</view>
		<scroll-view class="list-container" scroll-y="true" :style="{ height: `calc(100% - ${scrollHeight}px)` }">
			<view class="fund-list" v-if="showFund">
				<view class="list-item mine-flex padding bg-white solid-bottom" v-for="item in dataList"
					:key="item.code" @click="setting ? '' : detail(item)">
					<view class="flex-sub">
						<text>{{ item.name }}</text>
						<br />
						<text class="text-gray text-sm">{{ item.code }}</text>
					</view>
					<view v-if="!setting" class="flex-sub text-center">
						<text>{{ item.dayGrowth }}%</text>
					</view>
					<view v-if="!setting" class="flex-sub text-center">
						<text
							:class="item.expectGrowth >= 0 ? 'text-red' : 'text-green'">{{ openEye ? (item.expectGrowth  + '%') : '****' }}</text>
					</view>
					<view v-if="!setting" class="flex-sub text-center">
						<text :class="item.expectGrowth >= 0 ? 'text-red' : 'text-green'">{{
              openEye ? item.expectProceed : '****'
            }}</text>
					</view>
					<view v-if="setting" class="padding flex-sub sm-border text-center">
						<input @blur="changeShare($event, item)" placeholder="请填写持有金额"
							v-model="item.currentAmount" />
					</view>

					<view v-if="setting" class="flex-sub text-center">
						<text @click="remove(item.code)" class="cuIcon-deletefill text-red sm"></text>
					</view>
				</view>
			</view>
			<view class="stock-list" v-else>
				<view class="list-item flex padding bg-white solid-bottom" v-for="item in dataList" :key="item.code">
					<view class="flex-sub">
						<text>{{ item.name }}</text>
						<br />
						<text class="text-gray text-sm">{{ item.code }}</text>
					</view>
					<view v-if="!setting" class="flex-sub text-center">
						<text>{{ item.price }}</text>
					</view>
					<view v-if="!setting" class="flex-sub text-center">
						<text
							:class="item.changePercent >= 0 ? 'text-red' : 'text-green'">{{ item.changePercent }}%</text>
					</view>
					<view v-if="!setting" class="flex-sub text-center">
						<text
							:class="item.changePercent >= 0 ? 'text-red' : 'text-green'">{{ item.expectProceed }}</text>
					</view>
					<view v-if="setting" class="flex-sub text-center">
						<input @blur="changeShare($event, item)" placeholder="请填写持有金额" type="number"
							v-model="item.currentAmount" />
					</view>
					<view v-if="setting" class="flex-sub text-center">
						<text @click="remove(item.code)" class="cuIcon-deletefill text-red sm"></text>
					</view>
				</view>
			</view>
		</scroll-view>
		<view class="btnContainer">
			<yinrh-menu-float @menuClick="floatTouchClick" />
		</view>
	</view>
</template>
<script>
	import {
		mapGetters
	} from "vuex";
	export default {
		data() {
			return {
				openEye: true,
				proceed: 0,
				showFund: true,
				dataList: [],
				lastMonthDate: "", // 近30天日期
				setting: false, // 管理标的
				scrollHeight: 0,
				date: '####-##-##',
				touchEve: {},
				cardMargin: 0
			};
		},
		computed: {
			...mapGetters(["favor", "holding"]),
		},
		onLoad() {
			/* 设置前30天日期 */
			let time = new Date() - 1000 * 60 * 60 * 24 * 30;
			time = new Date(time);
			const m = (time.getMonth() + 1) > 9 ? time.getMonth() + 1 :  '0' + (time.getMonth() + 1);
			const d = (time.getDate()) > 9 ? time.getDate() :  '0' + (time.getDate());
			this.lastMonthDate =
				time.getFullYear() + "-" + m + "-" + d;
		},
		// 初次渲染后动态计算列表高度
		// onReady() {
		// 	let toolbarView = uni.createSelectorQuery().select(".toolbar");
		// 	toolbarView
		// 		.boundingClientRect((data) => {
		// 			let headerBox = uni.createSelectorQuery().select(".header-box");
		// 			headerBox
		// 				.boundingClientRect((data1) => {
		// 					this.scrollHeight = data.height + data1.height;
		// 				})
		// 				.exec();
		// 		})
		// 		.exec();
		// },
		onShow() {
			this.refreshList();
		},
		onPullDownRefresh() {
			this.pullAnimation = true;
			this.refreshList()
		},
		methods: {
			moveStart(e){
				this.touchEve = {
					startPointX: e.changedTouches[0].clientX,
					startPointY: e.changedTouches[0].clientY,
				}
			},
			moveEnd(e){
				this.touchEve.endPointX = e.changedTouches[0].clientX;
				this.touchEve.endPointY = e.changedTouches[0].clientY;
				const moveX = this.touchEve.endPointX - this.touchEve.startPointX;
				const moveY = this.touchEve.endPointY - this.touchEve.startPointY;
				if(Math.abs(moveX)> 50){
					const angle = Math.atan2(moveY, moveX) * 180 / Math.PI;
					if(angle>-45 && angle<45){
						this.cardMargin = 0;
						this.switchChannel(true);
					}else if(angle>135 ||angle<-135){
						this.cardMargin = '-100%'
						this.switchChannel(false);
					}
				}
			},
			// 切换基金股票
			switchChannel(flag) {
				this.showFund = flag;
				this.dataList = [];
				this.refreshList();
			},
			// 获取实时基金数据
			getCurrentFund() {
				if (!this.favor.fund.length || !this.showFund) {
					return;
				}
				uni.request({
					url: "https://api.doctorxiong.club/v1/fund/detail/list",
					data: {
						code: this.favor.fund.join(),
						startDate: this.lastMonthDate,
					},
					success: (res) => {
						this.date = res.data.data[0]?.netWorthDate || new Date().toLocaleDateString();
						const data = this.setShare(res.data.data, "fund");
						this.calcProceeds(data, "fund");
					},
				});
			},
			// 获取实时股票数据
			getCurrentStock() {
				if (!this.favor.stock.length || this.showFund) {
					return;
				}
				uni.request({
					url: "https://api.doctorxiong.club/v1/stock",
					data: {
						code: this.favor.stock.join(),
					},
					success: (res) => {
						const data = this.setShare(res.data.data, "stock");
						this.calcProceeds(data, "stock");
					},
				});
			},
			// 将持仓份额加入datalist  以便计算实时估值
			setShare(data, type) {
				this.holding[type].forEach((item) => {
					const target = data.find((e) => e.code === item.code);
					if (target) {
						target.share = item.share;
					}
				});
				return data;
			},
			// 计算当前持有金额
			showAmount() {
				const type = this.showFund ? "fund" : "stock";
				this.dataList.forEach((item) => {
					const share = this.holding[type].find(
						(e) => e.code === item.code
					)?.share;
					if (share) {
						item.currentAmount = ((item.netWorth || item.price) * share).toFixed(
							2
						);
					}
				});
			},
			// 计算预估收益
			calcProceeds(data, type) {
				let todayWorth = 0;
				if (this.holding[type].length) {
					const currentHolding = this.holding[type];
					currentHolding.forEach((item) => {
						// 持仓对应的实时数据
						const target = data.find((e) => e.code == item.code);
						// 计算预估收益
						if (type === "fund") {
							target.expectProceed = (
								(item.share * target.expectGrowth * target.netWorth) /
								100
							).toFixed(2);
						} else {
							target.expectProceed = (
								(item.share * target.price * target.changePercent) /
								100
							).toFixed(2);
						}
						// 今日预估总收益
						todayWorth += Number(target.expectProceed);
					});
				}
				this.proceed = todayWorth.toFixed(2);
				this.dataList = data;
				if (this.pullAnimation) {
					uni.stopPullDownRefresh()
					this.pullAnimation = false;
				}
				if (this.setting) {
					this.showAmount();
				}
			},
			floatTouchClick(eveNum) {
				switch (eveNum) {
					case 1: {
						this.add();
						break;
					};
				case 2: {
					this.config();
					break;
				};
				case 3: {
					this.config();
					break;
				}
				}
			},
			add() {
				uni.navigateTo({
					url: '/pages/mine/addList'
				})
			},
			config() {
				// 返回时
				if (this.setting) {
					this.refreshList();
				} else {
					// 设置时
					this.showAmount();
				}
				this.setting = !this.setting;
			},
			// 设置持仓信息
			changeShare(e, element) {
				if (e.target.value) {
					const code = element.code;
					const type = this.showFund ? "fund" : "stock";
					const item = this.holding[type].find((e) => e.code === code);
					const share = e.target.value / (element.netWorth || element.price);
					if (item) {
						item.share = share;
					} else {
						this.holding[type].push({
							code: code,
							share: share,
						});
					}
					this.$store.commit("setHolding", this.holding);
				}
			},
			remove(code) {
				const type = this.showFund ? "fund" : "stock";
				// 删除自选
				const idx = this.favor[type].findIndex((e) => e === code);
				this.favor[type].splice(idx, 1);
				// 删除自选对应的持仓信息
				const index = this.holding[type].findIndex((e) => e.code === code);
				if (index > -1) {
					this.holding[type].splice(index, 1);
				}
				this.$store.commit("setFavor", this.favor);
				this.$store.commit("setHolding", this.holding);
				uni.showToast({
					title: "操作成功",
				});
				this.dataList.splice(idx, 1);
			},
			refreshList() {
				this.showFund ? this.getCurrentFund() : this.getCurrentStock();
			},
			// 查看详情
			detail(item) {
				uni.navigateTo({
					url: `/pages/mine/detail?item=${JSON.stringify(item)}`,
				});
			},
		},
	};
</script>

<style lang="scss">
	view.cardContainer{
		display: flex;
		width: 200%;
		height: 220px;
		overflow: scroll;
		transition: margin-left 0.3s linear;
		flex-wrap: nowrap;
	}
	view.cardStock{
		background: linear-gradient(135deg, #2C32BE, #8D9BF3)!important;
	}
	view.card{
		width: 100%;
		background: linear-gradient(135deg, #6E60D9, #49B7E3);
		border-radius: 10px;
		margin: 15px;
		padding:30px;
		position: relative;
		overflow: hidden;
		view.line{
			display: flex;
			justify-content: space-between;
		}
		view.maskSqu{
			width: 200px;
			height: 200px;
			position: absolute;
			top: -100px;
			left: -100px;
			border: 40px solid #fff;
			opacity: 0.1;
		}
		view.cardTitle{
			color:#fff;
			font-size: 24px;
		}
		view.proceed{
			font-size: 32px;
			font-weight: bold;
			margin: 15px 0;
		}
		view.cardNumber{
			font-size: 12px;
			color: lightgray;
		}
		view.maskRou{
			width: 200px;
			height: 200px;
			border-radius: 50%;
			position: absolute;
			top: 100px;
			right: -100px;
			border: 40px solid #fff;
			opacity: 0.1;
		}
		view.eye{
			font-size: 24px;
			text-align: center;
			color: #fff;
			image{
				width: 24px;
				height: 24px;
			}
		}
		view.proceed{
			font-size: 32px;
			font-weight: bold;
			margin: 15px 0;
		}
		view.cardDate{
			font-size: 12px;
			font-weight: bold;
		}
	}
	.toolbar {
		display: flex;
		justify-content: space-between;
	}

	.btnContainer {
		position: fixed;
		left: 20px;
		bottom: 50px;
	}

	.mine-flex {
		display: flex;
		align-items: center;
	}

	.switch-box image {
		height: 30px;
		width: 30px;
	}
</style>
